{% extends "base.html" %}

{% block head %}
<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    .btn {
        padding: 8px 16px;
        border-radius: 4px;
        border: none;
        cursor: pointer;
        font-weight: 500;
        transition: background-color 0.2s;
    }

    .btn-primary {
        background-color: var(--primary-color);
        color: white;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
    }

    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }

    .spinner {
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #1976d2;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        display: none;
        margin-left: 10px;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .status-message {
        margin-top: 20px;
        padding: 15px;
        border-radius: 4px;
        display: none;
    }

    .status-message.success {
        background-color: #e8f5e9;
        color: #2e7d32;
        border: 1px solid #c8e6c9;
    }

    .status-message.error {
        background-color: #ffebee;
        color: #c62828;
        border: 1px solid #ffcdd2;
    }

    .loading {
        text-align: center;
        padding: 20px;
        display: none;
    }

    .loading.active {
        display: block;
    }

    /* 添加筛选区域样式 */
    .filter-area {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        padding: 20px;
        margin: 20px 0;
    }

    .filter-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid var(--border-color);
    }

    .filter-title {
        font-size: 16px;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .filter-section {
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 4px;
        border: 1px solid #e0e0e0;
    }

    .filter-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }

    .filter-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .filter-section-buttons {
        display: flex;
        gap: 8px;
    }

    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
    }

    .folder-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
    }

    .folder-item {
        background: var(--light-gray);
        padding: 8px 12px;
        border-radius: 4px;
        cursor: pointer;
        user-select: none;
        transition: background-color 0.2s;
    }

    .folder-item.selected {
        background: var(--primary-color);
        color: white;
    }

    .selection-box {
        margin-top: 20px;
        padding: 15px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .selection-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
    }

    .selection-title {
        font-size: 1.1rem;
        font-weight: 500;
        color: var(--primary-color);
    }

    .selection-list {
        max-height: 200px;
        overflow-y: auto;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        padding: 10px;
    }

    .selection-item {
        display: flex;
        align-items: center;
        padding: 6px 8px;
        cursor: pointer;
        user-select: none;
        transition: background-color 0.2s;
    }

    .selection-item:hover {
        background-color: var(--light-gray);
    }

    .selection-item.selected {
        background-color: #e3f2fd;
    }

    .selection-item input[type="checkbox"] {
        margin-right: 8px;
    }

    .relatives-select-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border: 1px solid var(--primary-color);
        color: var(--primary-color);
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;
    }

    .relatives-select-btn:hover {
        background: var(--primary-color);
        color: white;
    }

    .relatives-select-btn .selected-count {
        background: var(--primary-color);
        color: white;
        padding: 2px 6px;
        border-radius: 10px;
        font-size: 12px;
    }

    .relatives-select-btn:hover .selected-count {
        background: white;
        color: var(--primary-color);
    }

    /* 亲属选择模态框样式 */
    .modal {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
    }

    .modal-content {
        background-color: #fefefe;
        margin: 4% auto;
        padding: 25px;
        border: none;
        width: 90%;
        max-width: 1000px;
        border-radius: 8px;
        max-height: 85vh;
        overflow-y: auto;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: -25px -25px 20px;
        padding: 20px 25px;
        background: #f8f9fa;
        border-bottom: 1px solid #e0e0e0;
        border-radius: 8px 8px 0 0;
    }

    .modal-title {
        font-size: 1.25rem;
        font-weight: 500;
        color: var(--text-color);
        margin: 0;
    }

    .close-button {
        color: #666;
        font-size: 24px;
        font-weight: normal;
        cursor: pointer;
        transition: color 0.2s;
    }

    .close-button:hover {
        color: #333;
    }

    .relationship-tabs {
        margin: 0 -25px 20px;
        padding: 0 25px;
        background: #fff;
        border-bottom: 1px solid #e0e0e0;
        display: flex;
        gap: 0;
    }

    .relationship-tabs button {
        flex: 1;
        padding: 12px 24px;
        margin: 0;
        border: none;
        background: transparent;
        color: #666;
        cursor: pointer;
        font-size: 14px;
        font-weight: 500;
        position: relative;
        transition: all 0.2s;
        white-space: nowrap;
        text-align: center;
    }

    .relationship-tabs button:hover {
        color: var(--primary-color);
    }

    .relationship-tabs button.active {
        color: var(--primary-color);
    }

    .relationship-tabs button.active::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        width: 100%;
        height: 2px;
        background: var(--primary-color);
    }

    .relationship-panel {
        display: none;
        padding: 0;
        border: none;
        min-height: 300px;
        overflow-y: auto;
        max-height: calc(80vh - 200px);
    }

    .relationship-panel.active {
        display: block;
    }

    .relatives-section {
        margin-bottom: 20px;
        background: #fff;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        height: 100%;
    }

    .relatives-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        background: #f8f9fa;
        border-bottom: 1px solid #e0e0e0;
        border-radius: 8px 8px 0 0;
    }

    .relatives-section-title {
        font-size: 14px;
        font-weight: 500;
        color: #333;
    }

    .relatives-list {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
        padding: 20px;
        background: #fff;
        border-radius: 0 0 8px 8px;
    }

    .relationship-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 15px;
        background: #f8f9fa;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        transition: all 0.2s;
    }

    .relationship-item:hover {
        border-color: var(--primary-color);
        background: #fff;
    }

    .relationship-item input[type="checkbox"] {
        margin-right: 10px;
        width: 16px;
        height: 16px;
        cursor: pointer;
    }

    .relationship-item label {
        flex: 1;
        margin: 0;
        cursor: pointer;
        font-size: 14px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .relationship-type {
        font-size: 12px;
        color: #666;
        padding: 2px 8px;
        background: #e9ecef;
        border-radius: 12px;
        margin-left: 8px;
        white-space: nowrap;
    }

    .modal-footer {
        margin: 20px -25px -25px;
        padding: 15px 25px;
        background: #f8f9fa;
        border-top: 1px solid #e0e0e0;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
        border-radius: 0 0 8px 8px;
    }

    .modal-footer .btn {
        min-width: 80px;
    }

    .filter-section-buttons .btn {
        padding: 6px 12px;
        font-size: 13px;
    }

    /* 为三商清单添加特殊布局 */
    #businessPanel .relatives-list {
        grid-template-columns: repeat(2, 1fr);
    }

    /* 调整三商清单项目的样式 */
    #businessPanel .relationship-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 15px;
        background: #f8f9fa;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        transition: all 0.2s;
        gap: 10px;
    }

    #businessPanel .relationship-item:hover {
        border-color: var(--primary-color);
        background: #fff;
    }

    #businessPanel .relationship-item label {
        flex: 1;
        margin: 0;
        font-size: 14px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    #businessPanel .relationship-type {
        font-size: 12px;
        color: #666;
        padding: 2px 8px;
        background: #e9ecef;
        border-radius: 12px;
        white-space: nowrap;
        min-width: fit-content;
    }

    @media (max-width: 1200px) {
        .relatives-list {
            grid-template-columns: repeat(2, 1fr);
        }
        
        #businessPanel .relatives-list {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 768px) {
        .relatives-list {
            grid-template-columns: repeat(1, 1fr);
        }
        
        #businessPanel .relatives-list {
            grid-template-columns: repeat(1, 1fr);
        }
        
        .modal-content {
            width: 95%;
            margin: 2% auto;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>异常预警</h2>
        </div>
        <div class="card-body">
            <!-- 操作按钮 -->
            <div class="action-buttons">
                <button type="button" class="btn btn-primary" id="loadDataBtn">
                    加载已有数据
                    <div id="loadingSpinner" class="spinner"></div>
                </button>
            </div>

            <!-- 状态消息 -->
            <div id="statusMessage" class="status-message"></div>

            <!-- 筛选区域 -->
            <div id="filterArea" class="filter-area" style="display: none;">
                <div class="filter-header">
                    <h3 class="filter-title">筛选条件</h3>
                </div>
                <div class="filter-content">
                    <!-- 文件夹选择部分 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">选择被审查人：</div>
                            <div class="filter-section-buttons">
                                <button type="button" class="btn btn-sm btn-primary" id="selectAllFoldersBtn">全选</button>
                                <button type="button" class="btn btn-sm btn-primary" id="deselectAllFoldersBtn">取消全选</button>
                            </div>
                        </div>
                        <div id="folderList" class="folder-list"></div>
                    </div>

                    <!-- 亲属选择按钮 -->
                    <div class="filter-section">
                        <div class="filter-section-header">
                            <div class="filter-section-title">亲属/特定关系人/三商选择：</div>
                            <button type="button" class="relatives-select-btn" id="relativesSelectBtn">
                                选择
                                <span class="selected-count" id="selectedRelativesCount">0</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 亲属选择模态框 -->
            <div id="relativesModal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 class="modal-title">选择关系人</h3>
                        <span class="close-button" id="closeRelativesModal">&times;</span>
                    </div>
                    
                    <!-- 更新标签页切换按钮 -->
                    <div class="relationship-tabs">
                        <button type="button" class="active" data-tab="relatives">亲属关系</button>
                        <button type="button" data-tab="specific">特定关系人</button>
                        <button type="button" data-tab="business">三商清单</button>
                    </div>
                    
                    <!-- 亲属关系面板 -->
                    <div id="relativesPanel" class="relationship-panel active"></div>
                    
                    <!-- 特定关系人面板 -->
                    <div id="specificPanel" class="relationship-panel"></div>

                    <!-- 三商清单面板 -->
                    <div id="businessPanel" class="relationship-panel"></div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-primary" id="cancelRelativesSelection">取消</button>
                        <button type="button" class="btn btn-primary" id="confirmRelativesSelection">确定</button>
                    </div>
                </div>
            </div>

            <!-- 加载动画 -->
            <div id="loading" class="loading">
                正在加载数据，请稍候...
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const loadDataBtn = document.getElementById('loadDataBtn');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const statusMessage = document.getElementById('statusMessage');
    const filterArea = document.getElementById('filterArea');
    const folderList = document.getElementById('folderList');

    // 存储关系数据的Map
    let relativesMap = new Map();
    let specificRelationsMap = new Map();
    let businessListMap = new Map();
    let persistentSelectedRelatives = new Set();
    let persistentSelectedSpecific = new Set();
    let persistentSelectedBusiness = new Set();
    let tempSelectedRelatives = new Set();
    let tempSelectedSpecific = new Set();
    let tempSelectedBusiness = new Set();
    let currentTab = 'relatives';

    // 获取亲属选择相关的DOM元素
    const relativesModal = document.getElementById('relativesModal');
    const relativesSelectBtn = document.getElementById('relativesSelectBtn');
    const closeRelativesModal = document.getElementById('closeRelativesModal');
    const cancelRelativesSelection = document.getElementById('cancelRelativesSelection');
    const confirmRelativesSelection = document.getElementById('confirmRelativesSelection');
    const selectedRelativesCount = document.getElementById('selectedRelativesCount');

    // 标签页切换事件处理
    document.querySelectorAll('.relationship-tabs button').forEach(button => {
        button.addEventListener('click', (e) => {
            document.querySelectorAll('.relationship-tabs button').forEach(btn => {
                btn.classList.remove('active');
            });
            e.target.classList.add('active');

            document.querySelectorAll('.relationship-panel').forEach(panel => {
                panel.classList.remove('active');
                panel.style.display = 'none';
            });

            const tab = e.target.dataset.tab;
            let targetPanel;
            switch(tab) {
                case 'relatives':
                    targetPanel = document.getElementById('relativesPanel');
                    break;
                case 'specific':
                    targetPanel = document.getElementById('specificPanel');
                    break;
                case 'business':
                    targetPanel = document.getElementById('businessPanel');
                    break;
            }

            if (targetPanel) {
                targetPanel.classList.add('active');
                targetPanel.style.display = 'block';
                currentTab = tab;
                window.dispatchEvent(new Event('resize'));
            }
        });
    });

    // 修改加载数据函数
    async function loadFullData() {
        try {
            loadingSpinner.style.display = 'inline-block';
            loadDataBtn.disabled = true;
            document.getElementById('loading').classList.add('active');

            const response = await fetch('/abnormal-warning/load-data');
            const result = await response.json();

            if (result.success) {
                statusMessage.textContent = '数据加载成功';
                statusMessage.className = 'status-message success';
                statusMessage.style.display = 'block';

                // 清除现有数据
                relativesMap.clear();
                specificRelationsMap.clear();
                businessListMap.clear();
                
                // 显示文件夹列表
                folderList.innerHTML = '';
                result.folders.forEach(folder => {
                    const folderItem = document.createElement('div');
                    folderItem.className = 'folder-item';
                    
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.id = folder.name;
                    checkbox.value = folder.name;
                    checkbox.addEventListener('change', () => {
                        console.log(`[DEBUG] 文件夹 ${folder.name} 的选中状态改变`);
                        updateRelationshipList();
                    });
                    
                    const label = document.createElement('label');
                    label.htmlFor = folder.name;
                    label.textContent = folder.name;
                    
                    folderItem.appendChild(checkbox);
                    folderItem.appendChild(label);
                    folderList.appendChild(folderItem);

                    // 分别存储不同类型的关系数据
                    if (folder.relatives && Array.isArray(folder.relatives)) {
                        relativesMap.set(folder.name, folder.relatives);
                    }
                    if (folder.special_business && Array.isArray(folder.special_business)) {
                        // 分离特定关系人和三商清单
                        const specific = [];
                        const business = [];
                        folder.special_business.forEach(item => {
                            if (item[2] === '特定关系人') {
                                specific.push(item);
                            } else if (item[2] === '三商清单') {
                                business.push(item);
                            }
                        });
                        specificRelationsMap.set(folder.name, specific);
                        businessListMap.set(folder.name, business);
                    }
                });

                filterArea.style.display = 'block';
            } else {
                statusMessage.textContent = result.error || '加载数据失败';
                statusMessage.className = 'status-message error';
                statusMessage.style.display = 'block';
            }
        } catch (error) {
            console.error('Error:', error);
            statusMessage.textContent = '加载数据时出错';
            statusMessage.className = 'status-message error';
            statusMessage.style.display = 'block';
        } finally {
            loadingSpinner.style.display = 'none';
            loadDataBtn.disabled = false;
            document.getElementById('loading').classList.remove('active');
        }
    }

    // 更新关系列表函数
    function updateRelationshipList() {
        const relativesPanel = document.getElementById('relativesPanel');
        const specificPanel = document.getElementById('specificPanel');
        const businessPanel = document.getElementById('businessPanel');
        const selectedFolders = getSelectedFolders();

        // 清空所有面板
        relativesPanel.innerHTML = '';
        specificPanel.innerHTML = '';
        businessPanel.innerHTML = '';

        if (selectedFolders.length === 0) {
            const message = '<div style="text-align: center; padding: 20px;">请先选择被审查人</div>';
            relativesPanel.innerHTML = message;
            specificPanel.innerHTML = message;
            businessPanel.innerHTML = message;
            return;
        }

        // 更新亲属关系面板
        selectedFolders.forEach(folderName => {
            const relatives = relativesMap.get(folderName) || [];
            if (relatives.length > 0) {
                appendRelationshipSection(relativesPanel, folderName, relatives, 'relatives');
            }
        });

        // 更新特定关系人面板
        selectedFolders.forEach(folderName => {
            const specific = specificRelationsMap.get(folderName) || [];
            if (specific.length > 0) {
                appendRelationshipSection(specificPanel, folderName, specific, 'specific');
            }
        });

        // 更新三商清单面板
        selectedFolders.forEach(folderName => {
            const business = businessListMap.get(folderName) || [];
            if (business.length > 0) {
                appendRelationshipSection(businessPanel, folderName, business, 'business');
            }
        });

        // 确保当前活动面板可见
        const activeTab = document.querySelector('.relationship-tabs button.active');
        if (activeTab) {
            const tab = activeTab.dataset.tab;
            let targetPanel;
            switch(tab) {
                case 'relatives':
                    targetPanel = relativesPanel;
                    break;
                case 'specific':
                    targetPanel = specificPanel;
                    break;
                case 'business':
                    targetPanel = businessPanel;
                    break;
            }
            if (targetPanel) {
                targetPanel.style.display = 'block';
            }
        }

        updateSelectedCount();
    }

    // 添加关系部分到面板
    function appendRelationshipSection(panel, folderName, relationships, type) {
        const section = document.createElement('div');
        section.className = 'relatives-section';

        // 创建区域标题和按钮
        const header = document.createElement('div');
        header.className = 'relatives-section-header';

        const title = document.createElement('div');
        title.className = 'relatives-section-title';
        title.textContent = `${folderName} 的${type === 'relatives' ? '亲属' : type === 'specific' ? '特定关系人' : '三商清单'}`;

        const buttonGroup = document.createElement('div');
        buttonGroup.className = 'filter-section-buttons';

        const selectAllBtn = document.createElement('button');
        selectAllBtn.type = 'button';
        selectAllBtn.className = 'btn btn-sm btn-primary';
        selectAllBtn.textContent = '全选';
        selectAllBtn.onclick = () => selectAllInSection(folderName, type);

        const deselectAllBtn = document.createElement('button');
        deselectAllBtn.type = 'button';
        deselectAllBtn.className = 'btn btn-sm btn-primary';
        deselectAllBtn.textContent = '取消全选';
        deselectAllBtn.onclick = () => deselectAllInSection(folderName, type);

        buttonGroup.appendChild(selectAllBtn);
        buttonGroup.appendChild(deselectAllBtn);
        header.appendChild(title);
        header.appendChild(buttonGroup);
        section.appendChild(header);

        // 创建关系列表
        const list = document.createElement('div');
        list.className = 'relatives-list';
        list.id = `${type}-${folderName}`;

        relationships.forEach(item => {
            const itemDiv = document.createElement('div');
            itemDiv.className = 'relationship-item';
            
            const checkboxContainer = document.createElement('div');
            checkboxContainer.style.flex = '1';
            
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = `${type}-${folderName}-${item[0]}`;
            checkbox.value = item[0];
            checkbox.dataset.folder = folderName;
            checkbox.dataset.type = type;
            
            const label = document.createElement('label');
            label.htmlFor = checkbox.id;
            label.textContent = `${item[0]}（${item[1]}）`;
            
            checkboxContainer.appendChild(checkbox);
            checkboxContainer.appendChild(label);
            itemDiv.appendChild(checkboxContainer);

            // 如果是特定关系人/三商清单，添加类型标签
            if (type === 'specific' && item[2]) {
                const typeSpan = document.createElement('span');
                typeSpan.className = 'relationship-type';
                typeSpan.textContent = item[2];
                itemDiv.appendChild(typeSpan);
            }

            list.appendChild(itemDiv);
        });

        section.appendChild(list);
        panel.appendChild(section);
    }

    // 更新选中计数
    function updateSelectedCount() {
        const checkedRelatives = document.querySelectorAll('#relativesPanel input[type="checkbox"]:checked').length;
        const checkedSpecific = document.querySelectorAll('#specificPanel input[type="checkbox"]:checked').length;
        const checkedBusiness = document.querySelectorAll('#businessPanel input[type="checkbox"]:checked').length;
        selectedRelativesCount.textContent = checkedRelatives + checkedSpecific + checkedBusiness;
    }

    // 全选指定部分
    function selectAllInSection(folderName, type) {
        const selector = `#${type}-${folderName} input[type="checkbox"]`;
        const checkboxes = document.querySelectorAll(selector);
        checkboxes.forEach(cb => {
            cb.checked = true;
        });
        updateSelectedCount();
    }

    // 取消全选指定部分
    function deselectAllInSection(folderName, type) {
        const selector = `#${type}-${folderName} input[type="checkbox"]`;
        const checkboxes = document.querySelectorAll(selector);
        checkboxes.forEach(cb => {
            cb.checked = false;
        });
        updateSelectedCount();
    }

    // 修改打开模态框的处理
    relativesSelectBtn.addEventListener('click', () => {
        // 更新关系列表
        updateRelationshipList();
        
        // 保存当前选中状态
        tempSelectedRelatives = new Set(persistentSelectedRelatives);
        tempSelectedSpecific = new Set(persistentSelectedSpecific);
        tempSelectedBusiness = new Set(persistentSelectedBusiness);
        
        // 显示模态框
        relativesModal.style.display = 'block';
        
        // 确保默认显示第一个标签页
        const firstTab = document.querySelector('.relationship-tabs button');
        if (firstTab) {
            firstTab.click();
        }
    });

    // 修改确认按钮的处理
    confirmRelativesSelection.addEventListener('click', () => {
        // 更新持久化的选中状态
        persistentSelectedRelatives = new Set(
            Array.from(document.querySelectorAll('#relativesPanel input[type="checkbox"]:checked'))
                .map(cb => cb.value)
        );
        persistentSelectedSpecific = new Set(
            Array.from(document.querySelectorAll('#specificPanel input[type="checkbox"]:checked'))
                .map(cb => cb.value)
        );
        persistentSelectedBusiness = new Set(
            Array.from(document.querySelectorAll('#businessPanel input[type="checkbox"]:checked'))
                .map(cb => cb.value)
        );
        selectedRelativesCount.textContent = 
            persistentSelectedRelatives.size + 
            persistentSelectedSpecific.size + 
            persistentSelectedBusiness.size;
        relativesModal.style.display = 'none';
    });

    // 修改取消按钮的处理
    cancelRelativesSelection.addEventListener('click', () => {
        // 恢复之前的选中状态
        document.querySelectorAll('#relativesPanel input[type="checkbox"]').forEach(cb => {
            cb.checked = tempSelectedRelatives.has(cb.value);
        });
        document.querySelectorAll('#specificPanel input[type="checkbox"]').forEach(cb => {
            cb.checked = tempSelectedSpecific.has(cb.value);
        });
        document.querySelectorAll('#businessPanel input[type="checkbox"]').forEach(cb => {
            cb.checked = tempSelectedBusiness.has(cb.value);
        });
        relativesModal.style.display = 'none';
    });

    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === relativesModal) {
            relativesModal.style.display = 'none';
        }
    });

    // 关闭按钮事件
    closeRelativesModal.addEventListener('click', () => {
        relativesModal.style.display = 'none';
    });

    // 获取选中的文件夹
    function getSelectedFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    // 全选文件夹
    function selectAllFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = true;
        });
        updateRelationshipList();
    }

    // 取消全选文件夹
    function deselectAllFolders() {
        const checkboxes = folderList.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(cb => {
            cb.checked = false;
        });
        updateRelationshipList();
    }

    // 绑定按钮事件
    loadDataBtn.addEventListener('click', loadFullData);
    document.getElementById('selectAllFoldersBtn').addEventListener('click', selectAllFolders);
    document.getElementById('deselectAllFoldersBtn').addEventListener('click', deselectAllFolders);

    // 初始加载数据
    loadFullData();
});
</script>
{% endblock %} 